import {
  editDepartmentData,
  createDepartmentData,
  deleteDepartmentById,
  postDepartmentListData
} from '@/service/department/department'
import type { IDepartmentList } from '@/types/department/department'
import { notification } from '@/utils/notification'
import { defineStore } from 'pinia'

const useDepartmentStore = defineStore('department', {
  state: () => ({
    departmentList: [] as IDepartmentList[],
    totalCount: 0
  }),
  actions: {
    // 部门列表
    async postDepartmentListDataAction(data?: any) {
      // 1.获取部门列表数据
      const departmentListRes = await postDepartmentListData(data)

      // 2.存储部门列表数据
      const { list, totalCount } = departmentListRes.data
      this.departmentList = list
      this.totalCount = totalCount
    },
    // 删除部门
    async deleteDepartmentByIdAction(id: number) {
      // 1.调用接口
      const deletedepartmentRes = await deleteDepartmentById(id)

      // 2.消息提示
      if (deletedepartmentRes.code === 0) {
        // 2.1删除成功
        notification('success', deletedepartmentRes.data)
        // 2.2请求新的数据
        this.postDepartmentListDataAction({ size: 10, offset: 0 })
      } else {
        //2.3删除失败
        notification('error', deletedepartmentRes.data)
      }
    },
    // 新建部门
    async createDepartmentDataAction(userInfo: any) {
      // 1.调用接口
      const createdepartmentRes = await createDepartmentData(userInfo)

      // 2.消息提示
      if (createdepartmentRes.code === 0) {
        // 2.1新建成功
        notification('success', createdepartmentRes.data)
        // 2.2请求新的数据
        this.postDepartmentListDataAction({ size: 10, offset: 0 })
      } else {
        //2.3新建失败
        notification('error', createdepartmentRes.data)
      }
    },
    //编辑部门
    async editDepartmentDataAction(id: number, userInfo: any) {
      // 1.调用接口
      const editdepartmentRes = await editDepartmentData(id, userInfo)
      // 2.消息提示
      if (editdepartmentRes.code === 0) {
        // 2.1编辑成功
        notification('success', editdepartmentRes.data)
        // 2.2请求新的数据
        this.postDepartmentListDataAction({ size: 10, offset: 0 })
      } else {
        //2.3编辑失败
        notification('error', editdepartmentRes.data)
      }
    }
  }
})

export default useDepartmentStore
